package org.liubility.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jdragon.common.http.HttpException;
import com.jdragon.common.http.HttpUtils;;
import com.jdragon.common.json.JsonUtils;
import com.jdragon.common.response.normal.Result;
import org.liubility.pojo.dto.RobotMsgResult;
import org.liubility.pojo.entity.RobotPostOrder;

import java.util.List;
import java.util.Map;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.09.04 12:29
 * @Description:
 */
public class Api {
    public static String checkResult(Map<String, String> result) {
        String statusCode = result.get("statusCode");
        String resultStr = result.get("result");
        if ("200".equals(statusCode)) {
            return resultStr;
        } else {
            throw new HttpException(resultStr);
        }
    }

    public static RobotMsgResult robotHandle(String url, int request, String param, RobotMsgResult robotMsgResult) {
        HttpUtils httpUtils = HttpUtils.initJson();
        Map<String, String> map;

        if (robotMsgResult == null) return new RobotMsgResult();

        if (StrUtil.isNotBlank(param))
            robotMsgResult.setParam(param);
        String s = JsonUtils.object2Str(robotMsgResult);
        map = JSON.parseObject(s, new TypeReference<Map<String, String>>() {
        });
        if (request == 1) {
            httpUtils.setParamMap(map);
            map = httpUtils.get(url);
        } else {
            httpUtils.setBody(map);
            map = httpUtils.post(url);
        }
        Result<RobotMsgResult> result = JSON.parseObject(checkResult(map), new TypeReference<Result<RobotMsgResult>>() {
        });
        return result.getResult();
    }

    public static List<RobotPostOrder> getPostOrder() {
        HttpUtils httpUtils = HttpUtils.init();
        String resultStr = checkResult(httpUtils.get(Const.BASE_URL + Const.POST_ORDER));
        Result<List<RobotPostOrder>> result = JSON.parseObject(resultStr, new TypeReference<Result<List<RobotPostOrder>>>() {
        });
        return result.getResult();
    }
}
